package longrise.phone.com.bjjt_jyb.compensate;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.LFView;

import longrise.phone.com.bjjt_jyb.Activity.MainActivity;
import longrise.phone.com.bjjt_jyb.Application.BaseApplication;
import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.Utils.ApiImpI;
import longrise.phone.com.bjjt_jyb.Utils.DialogUtils;
import longrise.phone.com.bjjt_jyb.Utils.StringUtils;
import longrise.phone.com.bjjt_jyb.Utils.UiUtil;
import longrise.phone.com.bjjt_jyb.Utils.UiUtils;


/**
 * 生成协议书，Created by Administrator on 2016/5/12.
 */

public class CreateAgreementView extends LFView implements View.OnClickListener,ILFMsgListener,MainActivity.OnActivityReturnBitmap {
    private Context context = null;
    private View view = null;
    private BaseApplication mApplication;
    private EditText tv_createagreement2;
    private EditText tv_createagreement4;
    private TextView tv_createappointment1;
    private EntityBean[] CreateAgreementbean;
    private String appCaseno;
    private EditText et_createagreement1;
    // 对方请求签名
    private static final int OHER_REQUEST_CODE = 0x0022;
    private LinearLayout hn_btn_back;
    private ImageView iv_deletesign_he;
    private Bitmap bitmap;
    private Bitmap otherBitmap;
    private ImageView iv_createagreement_he;
    private Button bt_sign;
    private RelativeLayout rl_sign;
    private Button bt_createappointmenjf;
    private Button bt_createappointmenjf2;
    private RadioGroup rg_ifnosure1;
    private TimeCount time;
    private Integer fromwhere;
    private boolean refuse=false;//标识是否拒签。默认不拒签

    public CreateAgreementView(Context c, EntityBean[] beans, String appCaseno,Integer fromwhere) {
        super(c);
        this.context = c;
        this.mApplication = (BaseApplication) c.getApplicationContext();
        this.CreateAgreementbean = beans;
        this.appCaseno = appCaseno;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
        this.fromwhere=fromwhere;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_createagreementview, null);
        bt_createappointmenjf = (Button) view.findViewById(R.id.bt_createappointmenjf);
        bt_createappointmenjf2 = (Button) view.findViewById(R.id.bt_createappointmenjf2);
        bt_sign = (Button) view.findViewById(R.id.bt_sign);
        rl_sign = (RelativeLayout) view.findViewById(R.id.rl_sign);
        rg_ifnosure1 = (RadioGroup) view.findViewById(R.id.rg_ifnosure1);
        RadioButton rb_ifnosure_2 = (RadioButton) view.findViewById(R.id.rb_ifnosure_2);
        rb_ifnosure_2.setChecked(true);
        tv_createappointment1 = (TextView) view.findViewById(R.id.tv_createappointment1);
        //对方数据
        TextView tv_createagreement1 = (TextView) view.findViewById(R.id.tv_createagreement1);
        TextView tv_createagreement3 = (TextView) view.findViewById(R.id.tv_createagreement3);
        tv_createagreement2 = (EditText) view.findViewById(R.id.tv_createagreement2);
        tv_createagreement4 = (EditText) view.findViewById(R.id.tv_createagreement4);
        TextView tv_new4 = (TextView) view.findViewById(R.id.tv_new4);
        iv_createagreement_he = (ImageView) view.findViewById(R.id.iv_createagreement_he);//本方驾驶员签名图片
        iv_deletesign_he = (ImageView) view.findViewById(R.id.iv_deletesign_he);//对方驾驶员签名图片删除
        et_createagreement1 = (EditText) view.findViewById(R.id.et_createagreement1);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("生成认定书");//交警和远程定责生成责任认定书
        String userType = mApplication.getKckpUserType();
        if (null != userType && "9".equals(userType)) {
            //交警处理的案件，不能不认可
            bt_createappointmenjf2.setVisibility(View.GONE);
        }

        EntityBean otherBean=null;//对方信息
        for (EntityBean element:CreateAgreementbean) {
            String ownother =element.getString("ownother");
            if (TextUtils.equals(ownother, "1")) {
                otherBean = element;
            }
        }
        //对方数据
        String carownphone2 = (String) otherBean.get("carownphone");
        String dutytype2 = (String) otherBean.get("dutytype");
        String carownname2 = (String) otherBean.get("carownname");
        //String id2 = (String)otherBean.get("id");
        String casecarno2 = (String) otherBean.get("casecarno");

        if ("0".equals(dutytype2)) {
            tv_createagreement1.setText("全责");
        }
        if ("1".equals(dutytype2)) {
            tv_createagreement1.setText("无责");
        }
        if ("2".equals(dutytype2)) {
            tv_createagreement1.setText("同责");
        }
        if ("3".equals(dutytype2)) {
            tv_createagreement1.setText("主责");
        }
        if ("4".equals(dutytype2)) {
            tv_createagreement1.setText("次责");
        }
        tv_createagreement2.setText(carownname2);
        tv_createagreement3.setText(casecarno2);
        tv_createagreement4.setText(carownphone2);
        if(fromwhere==4||fromwhere==11){
            tv_new4.setText("车辆品牌");
        }

    }

    private void regEvent(boolean b) {
        if (null != bt_createappointmenjf) {
            bt_createappointmenjf.setOnClickListener(b ? this : null);
        }
        if (null != bt_createappointmenjf2) {
            bt_createappointmenjf2.setOnClickListener(b ? this : null);
        }
        if (null != tv_createappointment1) {
            tv_createappointment1.setOnClickListener(b ? this : null);
        }
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (null != iv_createagreement_he) {
            iv_createagreement_he.setOnClickListener(b ? this : null);
        }
        if (null != bt_sign) {
            bt_sign.setOnClickListener(b ? this : null);
        }
        if (null != iv_deletesign_he) {
            iv_deletesign_he.setOnClickListener(b ? this : null);
        }
        if (b) {
            this.addILFMsgListener(this);
        } else {
            this.removeILFMsgListener(this);
        }
        if (null != rg_ifnosure1) {
            rg_ifnosure1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int i) {
                    switch (i) {
                        case R.id.rb_ifnosure_1:
                            refuse=true;
                            break;
                        case R.id.rb_ifnosure_2:
                            refuse=false;
                            break;
                    }
                }
            });

        }
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            tv_createappointment1.setText("重发验证码");
            tv_createappointment1.setClickable(true);
            time.cancel();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            tv_createappointment1.setClickable(false);//防止重复点击
            tv_createappointment1.setText(millisUntilFinished / 1000 + "s");
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_createappointmenjf:
                String name = tv_createagreement2.getText().toString().trim();
                String phone = tv_createagreement4.getText().toString().trim();
                if(TextUtils.isEmpty(name)){
                    UiUtil.showToast(context, "姓名不能为空");
                    return;
                }
                if (!StringUtils.isPhone(phone)) {
                    UiUtil.showToast(context, "联系电话错误");
                    return;
                }
                if(!refuse){
                    if(null==otherBitmap){
                        UiUtil.showToast(context, "请甲方驾驶员签名");
                        return;
                    }
                    /**  去掉验证码只签名 **/
                    /*if(TextUtils.isEmpty(et_createagreement1.getText().toString().trim())){
                        UiUtil.showToast(context,"请填写甲方验证码");
                        return;
                    }*/
                }

               /* if(!refuse){
                    //如果没有拒签，就要联网判断验证码是否正确
                    code();
                }else {*/
                    //将修改的新的名字和电话传入集合中
                int j=0;
                for (int i = 0; i < CreateAgreementbean.length; i++) {
                    String ownother = CreateAgreementbean[i].getString("ownother");
                     if (TextUtils.equals(ownother, "1")) {
                         j=i;
                     }
                }
                CreateAgreementbean[j].set("carownname", name);
                CreateAgreementbean[j].set("carownphone", phone);
                CreateAgreementViewYF createagreementviewyf = new CreateAgreementViewYF(context,CreateAgreementbean,appCaseno,otherBitmap,et_createagreement1.getText().toString().trim(),refuse,fromwhere);
                FrameworkManager.getInstance().showNewForm(context, createagreementviewyf);//进入乙方填写页面
                //}
                break;
            case R.id.bt_createappointmenjf2:
                //报警
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri
                        .parse("tel:110"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().startActivity(intent);
                break;
            case R.id.tv_createappointment1:
                String hisPhone = tv_createagreement4.getText().toString().trim();
                if(!refuse){
                    getCode(hisPhone);//甲方获取验证码

                }else{
                    UiUtil.showToast(getContext(), "拒绝责任认定无须填写验证码");
                }
                break;
            case R.id.bt_sign:
                if(!refuse){
                    // 对方签名
                    // 跳转到签名的activity
                    Intent intent3 = new Intent(context, SignatureActivity.class);
                    if (context instanceof MainActivity) {
                        ((MainActivity) context).startActivityForResult(intent3,
                                OHER_REQUEST_CODE);
                    }
                }else{
                    UiUtil.showToast(getContext(), "拒绝责任认定无须签字确认");
                }
                break;
            case R.id.iv_deletesign_he://签名删除
                bt_sign.setVisibility(View.VISIBLE);//button显示
                rl_sign.setVisibility(View.GONE);
                break;
            case R.id.hn_btn_back:
                showHomeView();
                break;
        }
    }

    /**
     * 提示是否不继续处理，返回首页
     *
     */
    private void showHomeView() {
        UiUtils.showDialog(context, null, null, "是否放弃输入，结束本次快处并返回首页", "返回", "确认",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        closeAllForm();
                        OnDestroy();
                        HomePageView homepageview = new HomePageView(context);
                        FrameworkManager.getInstance().showNewForm(context, homepageview);
                    }
                });
    }

    /**
     * 获取验证码
     */
    private void getCode(String phonenum) {
        if (!StringUtils.isPhone(phonenum)) {
            Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(mApplication).getAgreementCode(phonenum, "11", new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                EntityBean bean = (EntityBean) result;
                String redes = bean.getString("redes");
                if (!TextUtils.isEmpty(redes)) {
                    UiUtil.showToast(getContext(), redes);
                    time = new TimeCount(60000, 1000);
                    time.start();// 开始计时
                }
            }
        });
    }
    @SuppressLint("NewApi")
    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            String bitmapByte = bundle.getString("bitmap");
            bitmap = BitmapFactory.decodeFile(bitmapByte);
            if (requestCode == OHER_REQUEST_CODE) {
                // 对面签名完成回调函数
                if (bitmapByte != null) {
                    bt_sign.setVisibility(View.GONE);
                    rl_sign.setVisibility(View.VISIBLE);
                    iv_createagreement_he.setImageBitmap(bitmap);
                    otherBitmap = bitmap;
                }
            }
        }
    }
    @Override
    public void OnDestroy() {
        super.OnDestroy();
        removeILFMsgListener(this);
        if(null!=bitmap){
            bitmap.recycle();
            bitmap=null;
        }
        view = null;
    }
    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {//点击返回按键
            showHomeView();
        }
        return false;
    }
}
